import { useEffect, useState, forwardRef, useImperativeHandle } from "react";
import { ScrollView, View } from "@tarojs/components";
import "./paging.scss";

function RuiPaging<T extends ListItem>(
  props: RuiPagingProps<T>,
  ref: React.ForwardedRef<RuiPagingRef<T>>
) {
  const {
    auto = true,
    onChange = () => {},
    size = 10,
    onQuery = () => {},
    children,
  } = props;
  const [page, setPage] = useState(1);
  const [isEnd, setIsEnd] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [list, setList] = useState<T[]>([]);
  useEffect(() => {
    if (auto && !isLoading) {
      setIsLoading(true);
      onQuery(page, size);
    }
  }, []);
  const onScrollToLower = () => {
    if (!isEnd && !isLoading) {
      setIsLoading(true);
      onQuery(page, size);
    }
  };
  const complete = (value: T[] | boolean) => {
    setIsLoading(false);
    if (Array.isArray(value)) {
      const newList = list.concat(value);
      onChange(newList);
      setList(newList);
      if (value.length < size) {
        setIsEnd(true);
      } else {
        setPage(page + 1);
      }
    } else {
      setIsEnd(true);
    }
  };
  const reload = () => {
    setPage(1);
    setList([]);
    setIsEnd(false);
    onQuery(1, size);
  };
  useImperativeHandle(ref, () => ({
    complete,
    reload,
  }));
  return (
    <ScrollView
      className="rui-paging-content"
      scrollY
      onScrollToLower={onScrollToLower}
    >
      {children}
      {list.length === 0 && isEnd && (
        <View className="rui-flex-cc h-[60px] text-[24px] text-[#999]">
          暂无数据
        </View>
      )}
      {isEnd && list.length > 0 && (
        <View className="rui-flex-cc h-[60px] text-[24px] text-[#999]">
          没有更多数据了
        </View>
      )}
      {isLoading && (
        <View className="rui-flex-cc h-[60px] text-[24px] text-[#999]">
          加载中...
        </View>
      )}
    </ScrollView>
  );
}

export default forwardRef(RuiPaging);
interface ListItem {}
export interface RuiPagingProps<T extends ListItem> {
  value?: T[];
  auto?: boolean;
  onChange: (e: T[]) => void;
  size?: number;
  onQuery: (page: number, size: number) => void;
  children: React.ReactNode;
}

export interface RuiPagingRef<T extends ListItem> {
  complete: (value: T[] | boolean) => void;
  reload: () => void;
}
